package com.lw.leetcode.arr.b;

/**289. 生命游戏
 * @Author liw
 * @Date 2021/6/28 13:43
 * @Version 1.0
 */
public class GameOfLife {
    private static final int[] DX = {0, 0, 1, -1, 1, 1, -1, -1};
    private static final int[] DY = {1, -1, 0, 0, 1, -1, 1, -1};

    public void gameOfLife(int[][] board) {
        if (board.length == 0) {
            return;
        }
        int n = board.length;
        int m = board[0].length;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                int cnt = 0;
                for (int k = 0; k < 8; k++) {
                    int x = i + DX[k];
                    int y = j + DY[k];
                    if (x < 0 || x == n || y < 0 || y == m) {
                        continue;
                    }
                    cnt += board[x][y] & 1;
                }
                if ((board[i][j] & 1) > 0) {
                    if (cnt >= 2 && cnt <= 3) {
                        board[i][j] = 0b11;
                    }
                } else if (cnt == 3) {
                    board[i][j] = 0b10;
                }
            }
        }
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                board[i][j] >>= 1;
            }
        }
    }

}
